//购物车store
import axios from "axios";
import { ElMessage, ElMessageBox } from 'element-plus'
import { defineStore } from "pinia";
import { ref, computed } from "vue";
export const useShopcartStore = defineStore('shopcart', () => {
  //获取购物车数据
  let shopcartList = ref([])
  const getShopcart = async () => {
    try {
      let res = await axios.get('/api/shopcartList')
      if (res.data.code == 200) {
        shopcartList.value = res.data.data
        //选中商品的信息也要同步更新
        updateCheckGoods(checkId.value)
      } else {
        console.log(res.data.message);
      }
    } catch (err) {
      console.log(err);
    }
  }
  getShopcart()
  //购物车数量修改
  const updateCartNum = async (id, num) => {
    try {
      let res = await axios.post('/api/updateCartNum', { id: id, num: num })
      if (res.data.code == 200) {
        getShopcart()
      } else {
        console.log(res.data.message);
      }

    } catch (err) {
      console.log(err);

    }
  }

  // 修改选中商品信息
  let checkGoods = ref([])
  // 保存选中商品的购物车id
  let checkId = ref([])
  
  const updateCheckGoods = (isChecked) => {
    checkId.value = isChecked
    checkGoods.value = shopcartList.value.filter(item => {
      return isChecked.includes(item.cart_id)
    })
  }

  //统计选中商品的总价
  const totalPrice = computed(() => {
    return checkGoods.value.reduce((total, item) => total + (item.num * item.price), 0)
  })

  //统计选中商品的数量
  const totalCount = computed(() => {
    return checkGoods.value.reduce((total, item) => total + item.num, 0)
  })

  //删除购物车商品

  const delShopcart = (id) => {
    ElMessageBox.confirm(
      '确定删除吗',
      '温馨提示',
      {
        confirmButtonText: 'OK',
        cancelButtonText: 'Cancel',
        type: 'warning',
      }
    )
      .then(async () => {
        try {
          let res = await axios.get(`/api/delCart?id=${id}`)
          if (res.data.code === 200) {
            ElMessage({
              message: '删除成功',
              type: 'success'
            })
            getShopcart()
          } else {
            console.log(res.data.message);
          }

        } catch (err) {
          console.log(err);
        }
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: 'Delete canceled',
        })
      })
  }

  // 增加商品数量
  const addCartNum = (id) => {
    const item = shopcartList.value.find(item => item.cart_id === id);
    if (item) {
      updateCartNum(id, item.num + 1);
    }
  }

  // 减少商品数量
  const subCartNum = (id) => {
    const item = shopcartList.value.find(item => item.cart_id === id);
    if (item && item.num > 1) {
      updateCartNum(id, item.num - 1);
    }
  }

  // 添加商品到购物车
  const addToCart = async (bookId, quantity = 1) => {
    try {
      if (!sessionStorage.getItem('token')) {
        return { success: false, message: '请先登录' };
      }
      const res = await axios.post('/api/addCart', {
        b_id: bookId,
        num: quantity
      });
      if (res.data.code === 200) {
        getShopcart();
        return { success: true, message: res.data.message || '添加到购物车成功' };
      } else {
        return { success: false, message: res.data.message || '添加到购物车失败' };
      }
    } catch (err) {
      return { success: false, message: '添加到购物车失败: ' + err.message };
    }
  }

  // 编辑购物车选中状态
  const editCartState = (id) => {
    const index = checkId.value.indexOf(id);
    if (index > -1) {
      checkId.value.splice(index, 1); // 取消选中
    } else {
      checkId.value.push(id); // 选中
    }
    updateCheckGoods(checkId.value);
  }

  // 全选/取消全选
  const isAllchecked = computed({
    get: () => {
      return shopcartList.value.length > 0 && checkId.value.length === shopcartList.value.length;
    },
    set: (val) => {
      if (val) {
        // 全选
        checkId.value = shopcartList.value.map(item => item.cart_id);
      } else {
        // 取消全选
        checkId.value = [];
      }
      updateCheckGoods(checkId.value);
    }
  });

  // 用于确认订单页面的选中商品列表
  let checkedList = ref([]);
  
  // 处理确认订单页面的商品数据
  const confirmOrder = () => {
    // 将选中的商品信息传递给确认订单页面
    checkedList.value = shopcartList.value.filter(item => {
      return checkId.value.includes(item.cart_id);
    });
    
    // 如果没有选中任何商品，提示用户
    if (checkedList.value.length === 0) {
      ElMessage({
        message: '请先选择要购买的商品',
        type: 'warning'
      });
    }
  }

  return {
    shopcartList,
    getShopcart,
    updateCartNum,
    checkGoods,
    checkId,
    updateCheckGoods,
    totalPrice,
    totalCount,
    delShopcart,
    addCartNum,
    subCartNum,
    addToCart,
    editCartState,
    isAllchecked,
    checkedList,
    confirmOrder
  }
})